package com.yxch.admin.interceptor;


import com.alibaba.fastjson.JSONObject;
import com.yxch.admin.utils.ResultAPI;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import com.yxch.admin.utils.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import static com.yxch.admin.utils.ExceptionEnum.NOT_LOGIN;
import static com.yxch.admin.utils.ExceptionEnum.TOKEN_ERROR;

@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {
    //true放行 false不放行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("prehandle>>>");
        //1.获取url
        String url = request.getRequestURI().toString();
        log.info("请求url:" + url);
        //2.判断是否为登录
        if (url.contains("login")) {
            log.info("登录...");
            return true;
        } else if (url.contains("register")) {
            log.info("注册...");
            return true;
        }
        //3.获取token
        String jwt = request.getHeader("Authorization");
        //4.token是否为空
        if (!StringUtils.hasLength(jwt)) {
            log.info("token为空，未登录");
            ResultAPI err = ResultAPI.error(NOT_LOGIN.getResultCode(), NOT_LOGIN.getResultMsg());
            //把响应数据变成json返回去
            String json = JSONObject.toJSONString(err);
            response.getWriter().write(json);
            return false;
        }
        //5.解析校验token
        try {
            JwtUtil.parseJWT(jwt.split(" ")[1]);
        } catch (Exception e) {
            e.printStackTrace();
            //令牌解析失败
            ResultAPI err = ResultAPI.error(TOKEN_ERROR.getResultCode(), TOKEN_ERROR.getResultMsg());
            log.info("令牌解析失败....");
            String json = JSONObject.toJSONString(err);
            response.getWriter().write(json);
            return false;
        }
        //6.令牌合法，放行
        log.info("令牌合法，放行");
        return true;
    }

    //放行后
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle>>>");
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion>>>");
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
